package com.shenchuangit.webprintclient.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtils {
    public static InputStream getRemoteFile(String fileUrl) {
        InputStream is = null;

        try {
            URL url = new URL(fileUrl);

            if (null != url) {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                int responseCode = connection.getResponseCode();
                if (200 == responseCode) {
                    is = connection.getInputStream();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return is;
    }

    public static File genFile(InputStream is) {
        String tmpPath = FileUtils.class.getResource("/").getPath();
        System.out.println(tmpPath);

        String fileName = String.valueOf(System.currentTimeMillis());

        File outFile = new File(tmpPath + fileName);

        int index;
        byte[] bytes = new byte[1024];
        try {

            FileOutputStream downloadFile = new FileOutputStream(outFile);

            while ((index = is.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            is.close();
            downloadFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return outFile;
    }
}
